package info.webest.media;

import android.annotation.TargetApi;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.util.Log;

public class MediaMetadata {

	public static String leftPad(int timeUnit) {
		String result = String.valueOf(timeUnit);
		for (int i = result.length(); i < 2; i++) {
			result = "0" + result;
		}
		return result;
	}

	public static String formatDuration(long duration) {

		String result = "";
		String seconds = String.valueOf((duration % 60000) / 1000);
		int minutes = (int) duration / 60000;
		int hours = 0;

		if (seconds.length() == 1) {
			seconds = "0" + seconds;
		}

		if (minutes > 60) {
			hours = (int) (minutes / 60);
			minutes = minutes - hours * 60;
		}

		result = leftPad(minutes) + ":" + seconds;
		if (hours > 0) {
			result = leftPad(hours) + ":" + result;
		}
		return result;
	}

	@TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
	public static String getDuration(String filePath) {

		MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
		String result = "";
		try {
			metaRetriever.setDataSource(filePath);

			// convert duration to minute:seconds
			String strDuration = metaRetriever
					.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
			Log.v("time", strDuration);
			long duration = Long.parseLong(strDuration);
			result = formatDuration(duration);
		} finally {
			// close object
			metaRetriever.release();
		}
		return result;
	}
}
